package com.base.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.soar.senv.SoarProperties;

/**
 * 系统入口过滤器 - 主要为'权限验证'
 * 
 * @author zhangaoxiang
 * @version $Revision: 1.1 $ - $Author: dingxude $ at $Date: 2014/05/09 07:59:12 $
 */
public class FilterSecurityInterceptor implements Filter
{
	private static final Log log = LogFactory.getLog(FilterSecurityInterceptor.class);

	public void destroy()
	{
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException
	{
		try
		{
			request.setCharacterEncoding("UTF-8"); // 统一请求字符编码
			response.setCharacterEncoding("UTF-8");
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse rep = (HttpServletResponse) response;
			HttpSession session = req.getSession();
			boolean loginFlag = session.getAttribute(SoarProperties.SOAR_BM_LOGINUSER_SESSION_ID) != null ? true : false;
			if (loginFlag)
			{ // 已登录，通过
				filterChain.doFilter(request, response);
			}
			else
			{
				String URI = req.getRequestURI();
				if (URI.indexOf("login.shtml") != -1)
				{
					filterChain.doFilter(request, response);
				}
				else
				{
					rep.sendRedirect(SoarProperties.SOAR_WEB_CONTEXTROOT + "/login.jsp");
				}
			}
		}
		catch (UnsupportedEncodingException e1)
		{
			log.error("Find UnsupportedEncodingException!");
			throw new ServletException(e1.getMessage());
		}
		catch (IOException e2)
		{
			log.error("Find IOException!");
			throw new ServletException(e2.getMessage());
		}
		catch (ServletException e3)
		{
			log.error("Find ServletException!");
			throw new ServletException(e3.getMessage());
		}
		catch (Exception e4)
		{
			log.error("Find Exception!");
			throw new ServletException(e4.getMessage());
		}
	}

	public void init(FilterConfig config) throws ServletException
	{
		log.info("SYS:初始化系统拦截器:FilterSecurityInterceptor...");
	}
}